import { Menu, MenuProps } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import logo from "@/assets/logo.png";
import styles from "./index.module.scss";
import { getMemuList, MenuResponse } from "@/services/api/user";
import menuIcons from "./iconList";
import { useLocation, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { StateType } from "@/store";
import listMenuByPath from "@/utils/listMenuByPath";

interface MenuItem {
  key: string;
  label?: string;
  icon?: React.ReactNode;
  children?: MenuItem[];
}

/** 转换菜单数据格式 */
function mapMenuItems(items: MenuResponse[]): MenuItem[] {
  return items.map((item) => ({
    key: item.key,
    label: item.label,
    icon: menuIcons[item.icon],
    children: item.children ? mapMenuItems(item.children) : undefined,
  }));
}

const NavMenu: React.FC = (props) => {
  const nav = useNavigate();

  // 菜单列表
  const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
  const menuList = useSelector((state: StateType) => state.authSlice.menuList);

  useEffect(() => {
    const menuItems = mapMenuItems(menuList);
    setMenuItems(menuItems);
  }, [menuList]);

  // 当前选中项
  const { pathname } = useLocation();
  const defaultOpenKey = useMemo(() => {
    const menus =  listMenuByPath(pathname, menuList);
    return menus[0]?.key;
  }, [pathname, menuList])

  // 点击跳转对应路由
  const onClick: MenuProps["onClick"] = ({ key }) => {
    nav(key);
  };

  return (
    <>
      <header className={styles["title-wrapper"]}>
        <Menu theme="dark" mode="inline" selectable={false}>
          <Menu.Item
            key="custom"
            title=""
            icon={<img src={logo} alt="" width={18} />}
            style={{ paddingLeft: "auto" }}
          >
            <h2>朋远智慧园区</h2>
          </Menu.Item>
        </Menu>
      </header>
      <main>
        <Menu
          defaultSelectedKeys={['/dashboard']}
          selectedKeys={[pathname]}
          defaultOpenKeys={[defaultOpenKey]}
          mode="inline"
          theme="dark"
          items={menuItems}
          onClick={onClick}
        />
      </main>
    </>
  );
};

export default NavMenu;
